package com.basic.util;

import static android.content.Context.ACTIVITY_SERVICE;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.util.Log;

public class MemTool {
	
	private static int totalMen;
	
	public static float getAvailMemMB(Context context){
		return   (getAvailMem(context) >> 10);
	}
	
	/**
	 * @param context
	 * @return 空余内存 单位k
	 */
	public static long getAvailMem(Context context) {
		ActivityManager am = (ActivityManager)context.getSystemService(ACTIVITY_SERVICE);
		MemoryInfo info = new MemoryInfo();
		am.getMemoryInfo(info);
		return info.availMem;
	} 
	
	/**
	 * @return 总内存 单位k
	 * @throws IOException
	 */
	public static synchronized long getTotalMem() throws IOException{
		if(totalMen == -1) {
			String line = null;
			BufferedReader br = null;
			try{
				//br = new BufferedReader(new InputStreamReader(process.getInputStream()), 128);
				br = new BufferedReader( new FileReader("/proc/meminfo"));
				line = br.readLine();
				Pattern pattern = Pattern.compile("\\d+");
				Matcher matcher = pattern.matcher(line);
				if(matcher.find()) {
					int value = Integer.parseInt(matcher.group());
					totalMen = value << 10;				
				} else {
					totalMen = 0;
				}
			} finally {
				if(br != null) br.close();
				//process.destroy();
			}
		}
		return totalMen;
	}
}
